﻿using AutoMapper;
using HelenServer.FileStorage.Contracts;
using HelenServer.Grpc.Contracts;

namespace HelenServer.FileStorage.Services;

[Injection(typeof(IFSMigrateQueue))]
public class FSMigateQueue : GrpcMethod<IEnumerable<KeyValuePair<int, IEnumerable<NotifySpiderGrpcModel>>>, GrpcResult<bool>>, IFSMigrateQueue
{
    private readonly IFileStorateMigrateQueueProvider _provider;
    private readonly IMapper _mapper;

    public FSMigateQueue(IFileStorateMigrateQueueProvider provider, IMapper mapper)
    {
        _provider = provider;
        _mapper = mapper;
    }

    public override Task<GrpcResult<bool>> InvokeAsync(IEnumerable<KeyValuePair<int, IEnumerable<NotifySpiderGrpcModel>>> request, ServerCallContext context)
    {
        try
        {
            var spiders = new List<KeyValuePair<int, IEnumerable<NotifySpiderModel>>>();

            foreach (var item in request)
            {
                spiders.Add(
                    new KeyValuePair<int, IEnumerable<NotifySpiderModel>>(
                        item.Key,
                        _mapper.Map<IEnumerable<NotifySpiderGrpcModel>, IEnumerable<NotifySpiderModel>>(item.Value)));
            }

            foreach (var spider in spiders)
            {
                _provider.Queue.Enqueue(spider);
            }

            Console.WriteLine($"迁移队列中目前有{_provider.Queue.Count}条记录");
        }
        catch (Exception ex)
        {
            return Task.FromResult(OperationResult<bool>.Failed(ex.Message).ToGrpcResult(r => r));
        }

        return Task.FromResult(OperationResult<bool>.OK(true).ToGrpcResult(r => r));
    }
}